package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author wusihao
 * @since 2022-12-15
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class) // 方便当异常出现的时候删除导入一半的数据
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("Excel导入成功!!!!");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        // 创建ExcelDictDTO列表，将Dict列表转换成ExcelDictDTO列表
        List<ExcelDictDTO> list = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, excelDictDTO);
            list.add(excelDictDTO);
        });
        return list;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        // 若redis服务器异常不要直接结束而是从数据库中取得数据
        try {
            // 查询redis中是否存在数据列表
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
                // 如果存在则从redis中直接返回数据列表
                if (dictList != null) {
                    log.info("从redis中取出数据");
                    return dictList;
                }

        } catch (Exception e) {
            log.info("redis服务器异常: " + ExceptionUtils.getStackTrace(e));
        }


        // 如果不存在则直接查询数据库
        log.info("从数据库中获取数据列表");
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        // 填充hasChildren字段
        dicts.forEach(dict -> {
            // 判断当前节点是否存在子节点, 找到当前dict夏季有没有子节点

            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        });

        try {
            log.info("将数据存入redis");
            // 将数据存入redis, 存储时间为5分钟
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dicts, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.info("redis服务器异常: " + ExceptionUtils.getStackTrace(e));
        }
        // 返回数据列表
        return dicts;
    }

    /*
    * 判断当前id所在的节点下是否有子节点
    * */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}
